package me.toalec.RankUp;

import me.toalec.RankUp.Permissions.PermissionsManager;
import me.toalec.RankUp.util.Utility;

import org.bukkit.Material;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;

public class SignTrigger extends PlayerListener{

	SignTrigger(RankUp instance, ConfigManager config, PermissionsManager pm){
		this.pm = pm;
		this.config = config;
	}
	
	public void onPlayerInteract(PlayerInteractEvent event){
		if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK)){
			if(event.getClickedBlock().getType().equals(Material.SIGN_POST) || event.getClickedBlock().getType().equals(Material.WALL_SIGN)){
				Sign sign = (Sign)event.getClickedBlock().getState();
				if(sign.getLine(0).equalsIgnoreCase("[RankUp]")){
					
					String packageName = sign.getLine(2);
					if(packageName.equals("")){packageName = "default";}
					
					if(config.getAllPackageNames().contains(packageName) && config.getBoolean(packageName + ".rankup_sign_enabled")){
						
						String startingGroup = config.getString(packageName + ".startingGroup");
						String endingGroup = config.getString(packageName + ".endingGroup");
						Player player = event.getPlayer();
						
						if( pm.isValidGroup(startingGroup, player) && pm.isValidGroup(endingGroup, player) ){
							if( pm.isValidPlayer(player.getName(), event.getPlayer()) && pm.getGroupName(player.getName(), player).contains(startingGroup) 
									&& !(pm.getGroupName(player.getName(), player).contains(endingGroup))){
								
								pm.removeGroup(player.getName(), player, startingGroup);
								pm.addGroup(player.getName(), player, endingGroup);
								
								Utility.messagePlayer(player, "Your rank has successfully been changed to " + endingGroup + ".");
							}else
								Utility.messagePlayer(player, "You are not in the correct Rank to use this sign.");
						}else{
							Utility.messagePlayer(player, "There is an issue with config.yml. Ask those who can, to check it.");
						}
					}else
						Utility.messagePlayer(event.getPlayer(), "Signs are not enabled for this package.");
				}
			}
		}
	}
	
	class SignPlace extends BlockListener{
		
		public void onSignChange(SignChangeEvent event){
			if(!event.isCancelled() && event.getLine(0).equalsIgnoreCase("[RankUp]")){
				if(!pm.hasPermission(event.getPlayer(), "rankup.signplace")){
					event.setCancelled(true);
					Utility.messagePlayer(event.getPlayer(), "You do not have permission to place [RankUp] signs.");
				}
			}
		}
	}
	
	private ConfigManager config;
	private PermissionsManager pm;
}
